package com.ruoyi.whole.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.AutofillUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.snowFlake.SnowFlakeUtil;
import com.ruoyi.fund.domain.DmsFund;
import com.ruoyi.fund.domain.DmsFundRecord;
import com.ruoyi.fund.service.IDmsFundRecordService;
import com.ruoyi.fund.service.IDmsFundService;
import com.ruoyi.whole.domain.DmsDealerVehicleInfo;
import com.ruoyi.whole.domain.DmsDealerWholePurchase;
import com.ruoyi.whole.domain.DmsDealerWholePurchaseDetail;
import com.ruoyi.whole.domain.vo.DmsDealerWholePurchaseVo;
import com.ruoyi.whole.mapper.DmsDealerWholePurchaseMapper;
import com.ruoyi.whole.service.IDmsDealerVehicleInfoService;
import com.ruoyi.whole.service.IDmsDealerWholePurchaseDetailService;
import com.ruoyi.whole.service.IDmsDealerWholePurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 车辆采购Service业务层处理
 * 
 * @author liuchuanfa
 * @date 2024-03-04
 */
@Service
public class DmsDealerWholePurchaseServiceImpl extends ServiceImpl<DmsDealerWholePurchaseMapper,DmsDealerWholePurchase> implements IDmsDealerWholePurchaseService
{
    @Autowired
    private DmsDealerWholePurchaseMapper dmsDealerWholePurchaseMapper;

    @Autowired
    private AutofillUtil autofillUtil;

    @Autowired
    private IDmsDealerWholePurchaseDetailService iDmsDealerWholePurchaseDetailService;

    @Autowired
    private IDmsDealerVehicleInfoService iDmsDealerVehicleInfoService;

    @Autowired
    private IDmsFundService iDmsFundService;

    @Autowired
    private IDmsFundRecordService iDmsFundRecordService;

    /**
     * 根据id查询车辆采购（返回给前端）
     *
     * @param id 车辆采购主键
     * @return 车辆采购
     */
    @Override
//    public DmsDealerWholePurchase selectDmsDealerWholePurchaseById(Long id)
    public DmsDealerWholePurchaseVo selectDmsDealerWholePurchaseById(Long id)
    {
//        return dmsDealerWholePurchaseMapper.selectDmsDealerWholePurchaseById(id);
        return dmsDealerWholePurchaseMapper.selectDmsDealerVehicleInfoByPurchaseId(id);
    }


    /**
     * 根据id查询车辆采购(后端自己用
     *
     * @param id
     * @return {@link DmsDealerWholePurchase }
     * @author liuchuanfa
     * @since 2024/03/05
     */
    public DmsDealerWholePurchase getDmsDealerWholePurchaseById(Long id)
    {
        return dmsDealerWholePurchaseMapper.selectDmsDealerWholePurchaseById(id);
    }

    /**
     * 查询车辆采购列表
     * 
     * @param dmsDealerWholePurchase 车辆采购
     * @return 车辆采购
     */
    @Override
    public List<DmsDealerWholePurchase> selectDmsDealerWholePurchaseList(DmsDealerWholePurchase dmsDealerWholePurchase)
    {
        return dmsDealerWholePurchaseMapper.selectDmsDealerWholePurchaseList(dmsDealerWholePurchase);
//        List<DmsDealerWholePurchase> list = lambdaQuery().eq(dmsDealerWholePurchase.getPurchaseId() != null, DmsDealerWholePurchase::getPurchaseId, dmsDealerWholePurchase.getPurchaseId())
//                .eq(dmsDealerWholePurchase.getCompanyId() != null, DmsDealerWholePurchase::getCompanyId, dmsDealerWholePurchase.getCompanyId())
//                .eq(dmsDealerWholePurchase.getDeptId() != null, DmsDealerWholePurchase::getDeptId, dmsDealerWholePurchase.getDeptId())
//                .eq(dmsDealerWholePurchase.getPurchaseStatus() != null, DmsDealerWholePurchase::getPurchaseStatus, dmsDealerWholePurchase.getPurchaseStatus())
//                .eq(dmsDealerWholePurchase.getWholePurchaseNumber() != null, DmsDealerWholePurchase::getWholePurchaseNumber, dmsDealerWholePurchase.getWholePurchaseNumber())
//                .like(dmsDealerWholePurchase.getAuditorName() != null, DmsDealerWholePurchase::getAuditorName, dmsDealerWholePurchase.getAuditorName())
//                .eq(dmsDealerWholePurchase.getAuditorId() != null, DmsDealerWholePurchase::getAuditorId, dmsDealerWholePurchase.getAuditorId())
//                .ge(dmsDealerWholePurchase.getAuditorTime() != null, DmsDealerWholePurchase::getAuditorTime, dmsDealerWholePurchase.getAuditorTime())
//                .eq(dmsDealerWholePurchase.getPaymentMethod() != null, DmsDealerWholePurchase::getPaymentMethod, dmsDealerWholePurchase.getPaymentMethod())
//                .list();
//        return list;
    }

    /**
     * 新增车辆采购
     * 
     * @param dmsDealerWholePurchase 车辆采购
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDmsDealerWholePurchase(DmsDealerWholePurchase dmsDealerWholePurchase)
    {
        //1. 判断采购新建状态是否为待审核，不是就报错 “新建时状态只能时待审核”
        if (!dmsDealerWholePurchase.getPurchaseStatus().equals(0)){
            throw new ServiceException("新建采购订单的状态只可以是待审核！");
        }
        //2. 必须至少有一个VIN
        if (dmsDealerWholePurchase.getDmsDealerWholePurchaseDetailList()!=null && dmsDealerWholePurchase.getDmsDealerWholePurchaseDetailList().size()==0){
            throw new ServiceException("新建采购订单至少需要一俩车！");
        }

        //新建采购单
        autofillUtil.autoFillCreate(dmsDealerWholePurchase);
        //添加经销商部门id，经销商公司id
        SysDept dept = SecurityUtils.getLoginUser().getUser().getDept();
        dmsDealerWholePurchase.setDeptId(dept.getDeptId());
        dmsDealerWholePurchase.setCompanyId(dept.getParentId());
        int rows = dmsDealerWholePurchaseMapper.insertDmsDealerWholePurchase(dmsDealerWholePurchase);
        insertDmsDealerWholePurchaseDetail(dmsDealerWholePurchase);
        return rows;
    }

    /**
     * 修改车辆采购
     * 
     * @param dmsDealerWholePurchase 车辆采购
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateDmsDealerWholePurchase(DmsDealerWholePurchase dmsDealerWholePurchase)
    {
        //根据采购订单id查询数据，比较状态是否逐层递进（不可跨状态,也不可逆
        DmsDealerWholePurchase dealerWholePurchase = getDmsDealerWholePurchaseById(dmsDealerWholePurchase.getId());
        Integer selectStatus = dealerWholePurchase.getPurchaseStatus();
        if (selectStatus>=dmsDealerWholePurchase.getPurchaseStatus()) throw new ServiceException("采购订单不可逆");
        if ((selectStatus+1)!=dmsDealerWholePurchase.getPurchaseStatus()) throw new ServiceException("采购订单不可跨状态修改");

        //判断修改时只能修改状态和添加备注和支付方式，不能改VIN
        List<DmsDealerWholePurchaseDetail> one = iDmsDealerWholePurchaseDetailService.lambdaQuery().eq(DmsDealerWholePurchaseDetail::getPurchaseId, dmsDealerWholePurchase.getId()).list();
        List<String> vin01 = one.stream().map(i -> i.getVin()).collect(Collectors.toList());
        List<String> vin02 = dmsDealerWholePurchase.getDmsDealerWholePurchaseDetailList().stream().map(i -> i.getVin()).collect(Collectors.toList());
//        if (!vin01.stream().allMatch(i -> vin02.contains(i)) && vin02.stream().allMatch(i -> vin01.contains(i)))
        if(! (vin01.size() == vin02.size() && vin01.containsAll(vin02)) ) throw new ServiceException("已经生成的采购订单不可修改vin！");

        dmsDealerWholePurchase.setUpdateTime(DateUtils.getNowDate());
        //采购表修改自动填充
        autofillUtil.autoFillUpdate(dmsDealerWholePurchase);
        //为采购表计算 采购车的数量、采购总价
        dmsDealerWholePurchase.setWholePurchaseNumber(dmsDealerWholePurchase.getDmsDealerWholePurchaseDetailList().size());
        double sumPrice = vin02.stream().mapToDouble(i -> {
                //根据vin，查询价格，并返回
                DmsDealerVehicleInfo vehicleInfo = iDmsDealerVehicleInfoService.lambdaQuery().eq(DmsDealerVehicleInfo::getVin, i).one();
                if (vehicleInfo==null){ throw new ServiceException("库存中查询不到该vin！"+i); }
                if (vehicleInfo.getPrice()==null){ throw new ServiceException("库存中查询不到该vin的价格！"+i);}
            return vehicleInfo.getPrice();
            }
        ).sum();
        dmsDealerWholePurchase.setPurchasePrice(sumPrice);
        //采购表添加 审核人、时间、人名
        dmsDealerWholePurchase.setAuditorId(SecurityUtils.getLoginUser().getUser().getUserId());
        dmsDealerWholePurchase.setAuditorName(SecurityUtils.getLoginUser().getUser().getUserName());
        dmsDealerWholePurchase.setAuditorTime(new Date());
        //业务要求：创建的采购订单无法修改，其中的VIN，所以注释以下两行代码
//        dmsDealerWholePurchaseMapper.deleteDmsDealerWholePurchaseDetailByPurchaseId(dmsDealerWholePurchase.getId());
//        insertDmsDealerWholePurchaseDetail(dmsDealerWholePurchase);
        dmsDealerWholePurchaseMapper.updateDmsDealerWholePurchase(dmsDealerWholePurchase);

        //修改车的状态
        List<DmsDealerWholePurchaseDetail> wholePurchaseDetailList = iDmsDealerWholePurchaseDetailService.lambdaQuery().eq(DmsDealerWholePurchaseDetail::getPurchaseId, dmsDealerWholePurchase.getPurchaseId()).list();
        List<String> vinList = wholePurchaseDetailList.stream().map(i -> i.getVin()).collect(Collectors.toList());
        //采购订单已发货就把车辆状态改为经销商在途
        if (dmsDealerWholePurchase.getPurchaseStatus().equals(6)){
            iDmsDealerVehicleInfoService.lambdaUpdate().set(DmsDealerVehicleInfo::getVehicleStatus,1).in(DmsDealerVehicleInfo::getVin,vinList).update();
        }
        //采购订单已签收，就改车辆状态为经销商在库
        if (dmsDealerWholePurchase.getPurchaseStatus().equals(7)){
            iDmsDealerVehicleInfoService.lambdaUpdate()
                    .set(DmsDealerVehicleInfo::getVehicleStatus,2)
                    .set(DmsDealerVehicleInfo::getInventoryType,"店端")
                    .in(DmsDealerVehicleInfo::getVin,vinList).update();
        }
        return 1;
    }

    /**
     * 批量删除车辆采购
     * 
     * @param ids 需要删除的车辆采购主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDmsDealerWholePurchaseByIds(Long[] ids)
    {
        dmsDealerWholePurchaseMapper.deleteDmsDealerWholePurchaseDetailByPurchaseIds(ids);
        return dmsDealerWholePurchaseMapper.deleteDmsDealerWholePurchaseByIds(ids);
    }

    /**
     * 删除车辆采购信息
     * 
     * @param id 车辆采购主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDmsDealerWholePurchaseById(Long id)
    {
        dmsDealerWholePurchaseMapper.deleteDmsDealerWholePurchaseDetailByPurchaseId(id);
        return dmsDealerWholePurchaseMapper.deleteDmsDealerWholePurchaseById(id);
    }

    /**
     * 新增车辆采购详细信息
     * 
     * @param dmsDealerWholePurchase 车辆采购对象
     */
    public void insertDmsDealerWholePurchaseDetail(DmsDealerWholePurchase dmsDealerWholePurchase)
    {
        List<DmsDealerWholePurchaseDetail> dmsDealerWholePurchaseDetailList = dmsDealerWholePurchase.getDmsDealerWholePurchaseDetailList();
        Long id = dmsDealerWholePurchase.getId();
        if (StringUtils.isNotNull(dmsDealerWholePurchaseDetailList))
        {
            List<DmsDealerWholePurchaseDetail> list = new ArrayList<DmsDealerWholePurchaseDetail>();
            Long detailId = SnowFlakeUtil.getDefaultSnowFlakeId();
            for (DmsDealerWholePurchaseDetail dmsDealerWholePurchaseDetail : dmsDealerWholePurchaseDetailList)
            {
                autofillUtil.autoFillCreate(dmsDealerWholePurchaseDetail);
                //由于时间太短，产生了重复的雪花id，所以这里自动填充填充雪花算法+1
                dmsDealerWholePurchaseDetail.setId(detailId++);
                dmsDealerWholePurchaseDetail.setPurchaseId(id);
                list.add(dmsDealerWholePurchaseDetail);
            }
            if (list.size() > 0)
            {
                dmsDealerWholePurchaseMapper.batchDmsDealerWholePurchaseDetail(list);
            }
        }
    }

    /**
     * 采购订单扣款
     *
     * @param dmsDealerWholePurchase
     * @return int
     * @author liuchuanfa
     * @since 2024/03/08
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int purchaseDeduct(DmsDealerWholePurchase dmsDealerWholePurchase) {
        //1.获取经销商id(广州/深圳经销商），进行扣款
        long companyId = dmsDealerWholePurchase.getCompanyId();
        Double purchasePrice = dmsDealerWholePurchase.getPurchasePrice(); //采购总价
        //查询经销商的资金并判断是否够钱，够才更新数据
        //① 不够钱
        DmsFund dmsFund = new DmsFund();
        dmsFund.setFundOwnerId(companyId);
        List<DmsFund> dmsFundList = iDmsFundService.selectDmsFundList(dmsFund);
        if (CollUtil.isEmpty(dmsFundList)){
            throw new ServiceException("查询不到账户："+companyId);
        }
        dmsFund = dmsFundList.get(0);
        Double fund = dmsFund.getFund();
        Double fundResult = fund-purchasePrice;
        if (fundResult < 0.00){
            throw new ServiceException("账户："+companyId+" 金额不足，无法扣款");
        }
        //② 够钱
        dmsFund.setFund(fundResult);
        iDmsFundService.updateDmsFund(dmsFund);

        //2.把扣款记录写入，资金记录表
        DmsFundRecord dmsFundRecord = new DmsFundRecord();
        dmsFundRecord.setFundOwnerId(companyId);
        //填入资金方所属方名称、和类型
        if(companyId==201){
            dmsFundRecord.setFundOwnerType(0);
            dmsFundRecord.setFundOwnerName(0);
        }
        else if (companyId==101){
            dmsFundRecord.setFundOwnerType(1);
            dmsFundRecord.setFundOwnerName(1);
        }
        else if (companyId==102){
            dmsFundRecord.setFundOwnerType(1);
            dmsFundRecord.setFundOwnerName(2);
        }
        dmsFundRecord.setConsumerFund(purchasePrice);
        dmsFundRecord.setConsumerId(SecurityUtils.getLoginUser().getUser().getUserId());
        dmsFundRecord.setConsumerName(SecurityUtils.getLoginUser().getUser().getUserName());
        dmsFundRecord.setConsumerTime(new Date());
        iDmsFundRecordService.updateDmsFundRecord(dmsFundRecord);

        //修改状态
        return updateDmsDealerWholePurchase(dmsDealerWholePurchase);
    }
}
